var app = getApp()
Page({
  data: {
    getuser: -1
  },

  onLoad: function() {
    1
  },

  goHome: function() {
    wx.switchTab({
      url: "/pages/index/index"
    });
  },

  onShow() {
    var that = this;

    // 验证sessionId是否过期
    that.loadCheckSessionId();

    // 授权状态
    if (wx.getStorageSync('getuser')) {
      this.setData({
        getuser: wx.getStorageSync('getuser'),
        userInfo: app.globalData.userInfo
      })
    }
  },

  // 验证sessionId是否过期
  loadCheckSessionId: function() {
    var that = this;
    // wx.showLoading({
    //   title: '加载中...',
    //   mask: true
    // })
    app.getData(
      app.getApiUrl("xcxapi/checkSessionId"),
      true, {
        app_mini_id: app.globalData.app_mini_id
      }, {
        success: function(res) {
          if (res.data.code == 200 && app.globalData.openid != '') {
            wx.hideLoading();
          } else {
            // 用户登录
            app.wxLogin(function() {
              wx.hideLoading();
            });
          }
        },
        fail: function(res) {
          that.loadCheckSessionId();
        }
      }
    )
  },



  // 用户授权
  wxUserInfo: function(e) {
    var that = this;
    app.wxUserInfo(e.detail.userInfo, function() {
      wx.setStorageSync('userInfo', e.detail.userInfo);
      if (!wx.getStorageSync('getuser')) {
        wx.setStorageSync('getuser', 1)
      }
      that.setData({
        userinfo: e.detail.userInfo,
        showPhone: 1,
        getuser: 1,

      })
    });
  },
  //获取手机号
  getPhoneNumber: function(e) {
    var that = this
    wx.login({
      success: res => {
        if (res.code) {
          console.log(e);
          wx.request({
            header: {
              'Cookie': 'PHPSESSID=' + app.globalData.sessionId
            },
            method: 'POST',
            url: app.getApiUrl("xcxapi/phone"),
            data: {
              encryptedData: e.detail.encryptedData,
              iv: e.detail.iv,
              signature: e.detail.signature,
              code: res.code
            },
            success: function(r) {
                wx.showToast({
                  title: "绑定成功",
                });
                wx.hideLoading(), wx.navigateBack({
                  delta: 2 //返回指定页面 
                  });
            },
            fail: function() {
              wx.showModal({
                title: "提示",
                content: "绑定失败",
              });
            }
          });
        } else {
          wx.showModal({
            title: "提示",
            content: "授权失败"
          });
        }
      }
    });
  },

  // 设置页面转发信息
  onShareAppMessage: function(res) {
    return {
      title: '自定义转发标题',
      path: '/pages/index/index',
      success: function(e) {
        console.log(e)
      },
      fail: function(e) {
        // 转发失败
      }
    }
  }
})